﻿using System.Net.WebSockets;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using StudyCompanion.Core.API;
using StudyCompanion.Core.Models;
using StudyCompanion.Core.Share;
using StudyCompanion.IServices;

namespace StudyCompanion.WebApi.Controllers;

/// <summary>
/// </summary>
[Route("api/[controller]")]
[ApiController]
public class ChatGPTController : ApiController
{
    private readonly IHubContext _hubContext;
    private readonly IUserContext _userContext;
    private readonly IUserService _userService;

    /// <summary>
    /// </summary>
    /// <param name="userService"></param>
    /// <param name="userContext"></param>
    public ChatGPTController(IUserService userService
        , IUserContext userContext
        , IHubContext hubContext)
    {
        _userService = userService;
        _userContext = userContext;
        _hubContext = hubContext;
    }

    /// <summary>
    ///     提问
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost("query")]
    public async Task Query(SimpleDto<string> input)
    {
        await _hubContext.Clients.Group(_userContext.Id.ToString()).SendAsync("answer", "data:收到消息");
        Thread.Sleep(1000);
        await _hubContext.Clients.Group(_userContext.Id.ToString()).SendAsync("answer", "[DONE]");
        //if (HttpContext.WebSockets.IsWebSocketRequest)
        //{
        //    var user = await _userService.GetUserbyId(_userContext.Id);
        //    if (user == null && user.ValidTime <= DateTime.Now)
        //        HttpContext.Response.StatusCode = StatusCodes.Status405MethodNotAllowed;
        //    using var webSocket = await HttpContext.WebSockets.AcceptWebSocketAsync();

        //    var client = new HttpClient();
        //    var uri = new Uri("");
        //    var content = JsonContent.Create(new ChatGPTQueryDto {UserId = _userContext.Id,Query = input.Value});
        //    using var request = new HttpRequestMessage(HttpMethod.Post, uri);
        //    request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("text/event-stream"));
        //    request.Content = content;
        //    var responseTask = client.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
        //    var response = responseTask.GetAwaiter().GetResult();
        //    await using var stream = await response.Content.ReadAsStreamAsync();
        //    using var reader = new StreamReader(stream);
        //    while (!reader.EndOfStream)
        //    {
        //        var line = await reader.ReadLineAsync();
        //        if (string.IsNullOrEmpty(line))
        //            continue;
        //        var buffer = Encoding.Unicode.GetBytes(line);
        //        await webSocket.SendAsync(new ArraySegment<byte>(buffer, 0, buffer.Length), WebSocketMessageType.Text,true,CancellationToken.None);
        //    }
        //    await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, null, CancellationToken.None);
        //}
        //else
        //{
        //    HttpContext.Response.StatusCode = StatusCodes.Status400BadRequest;
        //}
    }

    private static async Task Echo(WebSocket webSocket)
    {
        var buffer = new byte[1024 * 4];
        var receiveResult = await webSocket.ReceiveAsync(
            new ArraySegment<byte>(buffer), CancellationToken.None);

        while (!receiveResult.CloseStatus.HasValue)
        {
            await webSocket.SendAsync(
                new ArraySegment<byte>(buffer, 0, receiveResult.Count),
                receiveResult.MessageType,
                receiveResult.EndOfMessage,
                CancellationToken.None);

            receiveResult = await webSocket.ReceiveAsync(
                new ArraySegment<byte>(buffer), CancellationToken.None);
        }

        await webSocket.CloseAsync(
            receiveResult.CloseStatus.Value,
            receiveResult.CloseStatusDescription,
            CancellationToken.None);
    }
}